var ifbtn = 0;
var pm_data = getdata();
autosize($("textarea.autosize"));
if (typeof(FormData) == 'undefined') {
    $("li.low_tip").show();
}
if (! (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE", "")) < 9)) {
    $("#dragsort").dragsort({
        dragSelector: "blockquote",
        dragSelectorExclude: "input,textarea,a",
        dragBetween: true,
        dragEnd: orderNumber,
        scrollSpeed: 5
    });
}
if ($("#cover div").length > 0) {
    $("#cover").dragsort({
        dragSelector: "div",
        dragSelectorExclude: "input,textarea,a",
        dragBetween: true,
        scrollSpeed: 5
    });
}
$("#cover").on("click", "a.del",
    function() {
        var that = $(this);
        var img = that.parent().find('img');
        if ($("#cover div").length == 1) {
            msc.ui.dialog.error("请至少保留一张成品图片");
            return false;
        }
        if (img.hasClass('imgLoad')) {
            msc.ui.dialog.alert("确定要删除该图片么？",
                function() {
                    delAliYunObject(img.attr('src'));
                    that.parent().fadeOut('400',
                        function() {
                            $(this).remove();
                            timesave(1);
                        });
                },
                $.noop);
        } else {
            delAliYunObject(img.attr('src'));
            that.parent().fadeOut('400',
                function() {
                    $(this).remove();
                });
        }
    });
$(".options_box div").click(function() {
    var n = $(this).index();
    $(".options_item div:eq(" + n + ")").slideDown().siblings().hide();
});
$(".options_item div span").click(function() {
    var n = $(this).parent().index();
    if (n == 2) {
        var c = [],
            d = [];
        if ($(this).hasClass('on'))
            $(this).removeClass('on')
        else {
            if ($(".options_item div:eq(2) span.on").length < 5) {
                $(this).addClass('on');
            } else {
                msc.ui.dialog.error("最多选5个");
                return false;
            }
        }
        $(".options_item div:eq(2) span").each(function() {
            if ($(this).hasClass('on')) {
                c.push($(this).attr('data-value'));
                d.push($(this).html());
            }
        });
        $(".options_box div:eq(2)").find('input').val(c.join(','));
        $(".options_box div:eq(2)").find('span').html(d.join('，')).attr('title', d.join('，'));
    } else {
        $(".options_box div:eq(" + n + ")").find('input').val($(this).attr('data-value'));
        $(".options_box div:eq(" + n + ")").find('span').html($(this).html()).attr('title', $(this).html());
        $(this).addClass('on').siblings().removeClass('on');
    }
});
$("li.ingredient").on("focus", "input",
    function() {
        if ($(this).parent().hasClass('J_addDiv')) {
            $(this).parent().after('<div class="J_addDiv"><input type="text" class="liao"  autocomplete="off">' + '<input type="text" class="yongliang"   autocomplete="off">' + '<a href="javascript:void(0);" class="delete J_delete"></a></div>');
            $(this).parent().removeClass('J_addDiv');
        }
    });
$("li.ingredient").on("click", "a.delete",
    function() {
        if ($(this).parent().hasClass('J_addDiv')) $(this).parent().prev().addClass('J_addDiv');
        $(this).parent().remove();
    });

$("#dragsort").on("click", "a",
    function() {
        var th = $(this);
        if (th.hasClass('J_delTextarea')) {
            var pa = th.closest('.J_blockQ');
            var img = pa.find("img.file_img").attr("src");
            if ($(".J_blockQ").length > 3) {
                var stepid = pa.attr('data-id');
                if (stepid) {
                    msc.ui.dialog.alert("删除步骤后将无法恢复,您确定要删除么?",
                        function() {
                            $.post(msc.tools.getAjaxUrl({
                                    ac: "recipe",
                                    op: "delete_steps_pic"
                                }), {
                                    recipeid: $("#recipeinfo_id").val(),
                                    stepid: stepid
                                },
                                function(d) {
                                    if (d.error == 0) {
                                        pa.fadeOut('800',
                                            function() {
                                                pa.remove();
                                                orderNumber();
                                            });
                                        if (img) {
                                            delAliYunObject(img);
                                        }
                                    } else msc.ui.dialog.error("出现错误，请重试");
                                },
                                "json");
                        },
                        $.noop);
                } else {
                    pa.fadeOut('800',
                        function() {
                            pa.remove();
                            orderNumber();
                            if (img) {
                                delAliYunObject(img);
                            }
                        });
                }
            } else msc.ui.dialog.error("您至少需要填写三步");
        } else if (th.hasClass('J_upTextarea')) {
            var sn = th.parent().parent().index();
            if (sn > 0) {
                sn -= 1;
                $('#dragsort').find('blockquote:eq(' + sn + ')').before(th.parent().parent().clone().hide());
                $('#dragsort').find('blockquote:eq(' + sn + ')').fadeIn('800');
                th.closest('.J_blockQ').remove();
                orderNumber();
            }
        } else if (th.hasClass('J_downTextarea')) {
            var sn2 = th.parent().parent().index();
            if (sn2 != $('#dragsort blockquote').length - 1) {
                sn2++;
                $('#dragsort').find('blockquote:eq(' + sn2 + ')').after(th.parent().parent().clone().hide());
                sn2++;
                $('#dragsort').find('blockquote:eq(' + sn2 + ')').fadeIn('800');
                th.closest('.J_blockQ').remove();
                orderNumber();
            }
        } else if (th.hasClass('J_addTextarea')) {
            th.closest('.J_blockQ').after('<blockquote class="cp_block J_blockQ clear" style="display:none;cursor:move;"><div class="left addicon J_fileImag" ><input type="hidden" value="" name="step_img" class="J_imghidden" /><input type="file" name="file"  accept="image/png,image/gif,image/jpeg" class="file" /><p class="p1">点击上传步骤图</p><p class="p3">（可不填）</p></div><div class="right"><input type="hidden" name="stepid" value=""><textarea name="note" class="textArea J_input" placeholder="请输入步骤说明"></textarea><span class="J_step_num"></span><a href="javascript:void(0);" class="add J_addTextarea">&nbsp;添加一步&nbsp;</a><a class="up J_upTextarea" href="javascript:void(0);">&nbsp;上移一步&nbsp;</a><a class="down J_downTextarea" href="javascript:void(0);">&nbsp;下移一步&nbsp;</a><a href="javascript:void(0);" class="delete J_delTextarea">&nbsp;删除本步&nbsp;</a></div></blockquote>');
            th.parent().parent().next().slideDown('600');
            orderNumber();
        }
    });
$("#J_m_cover").click(function() {
    $(this).val('');
});
$("#J_m_cover").change(function() {
    var imgs = $(this).get(0).files;
    var n = 9 - $("#cover div").length;
    if (imgs.length > n) {
        msc.ui.dialog.error("当前还能上传" + n + "张图片");
        $(this).val('');
        return false;
    } else {
        img_status(1, 0, imgs.length);
        upload_img(imgs, 1, 0);
    }
});
$("#J_s_cover").click(function() {
    $(this).val('');
});
$("#J_s_cover").change(function() {
    var imgs = $(this).get(0).files;
    img_status(2, 0, imgs.length);
    upload_img(imgs, 2, 0);
});
$("#dragsort").on('click', 'input.file',
    function() {
        $(this).val('');
    });
$("#dragsort").on('change', 'input.file',
    function() {
        var img = $(this).get(0).files;
        var p = $(this).parent();
        if (p.find('.file_img').length > 0) p.find('.file_img').hide();
        else p.append('<div class="div_file_img"><b></b></div>');
        upload_img(img, 3, 0, p);
    });
function upload_img(f, type, i, p) {
    var formData = new FormData($('#form')[0]);
    var key = $("#oss_key").val();
    var uid = $("#user_id").val();
    var j = f[i].name.substring(f[i].name.lastIndexOf('.') + 1);
    key = key + (new Date().getTime()) + Math.floor(Math.random() * 1000) + uid + "." + j;
    formData.append("key", key);
    formData.append("file", f[i]);
    console.log(formData)
    $.ajax({
        url: "/recipes/file",
        type: "POST",
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        success: function(res) {
            if (type == 1) {
                img_status(1, 1);
                $("#cover").append(`<div style="display:none;"><a class="del" href="javascript:void(0);" >删除</a><span></span><img src=${res.url}><input type="hidden" name="allpic" value=${res.url}></div>`);
                $("#cover div:last").fadeIn('600');
                if ($("#cover div").length == 1) $("#cover").dragsort({
                    dragSelector: "div",
                    dragBetween: true,
                    scrollSpeed: 5
                });
            } else if (type == 2) {
                img_status(2, 1);
                var n = add_stepimg_number();
                if (n == -1) {
                    $("#dragsort").append(`<blockquote class="cp_block J_blockQ clear" ><div class="left addicon J_fileImag" ><input type="hidden" value=${res.url}  name="step_img" class="J_imghidden" /><input type="file" name="file"  class="file" /><p class="p1">点击上传步骤图</p><p class="p3">（可不填）</p><div class="div_file_img"><b></b><img class="file_img" src=${res.url}></div></div><div class="right"><input type="hidden" name="stepid" value=""><textarea name="note" class="textArea J_input" placeholder="请输入步骤说明"></textarea><span class="J_step_num"></span><a href="javascript:void(0);" class="add J_addTextarea">&nbsp;添加一步&nbsp;</a><a class="up J_upTextarea" href="javascript:void(0);">&nbsp;上移一步&nbsp;</a><a class="down J_downTextarea" href="javascript:void(0);">&nbsp;下移一步&nbsp;</a><a href="javascript:void(0);" class="delete J_delTextarea">&nbsp;删除本步&nbsp;</a></div></blockquote>`);
                } else {
                    $("#dragsort blockquote:eq(" + n + ")").find('.addicon').append(`<div class="div_file_img"><b></b><img class="file_img" src=  ${res.url} ></div>`);
                    $("#dragsort blockquote:eq(" + n + ")").find('input[name=step_img]').val(  res.url);
                }
                orderNumber();
            } else if (type == 3) {
                p.find('input.J_imghidden').val( res.url);
                if (p.find('.file_img').length > 0) {
                    p.find('.file_img').attr('src', res.url).show();
                } else p.append(`<div class="div_file_img"><b></b><img class="file_img" src=${res.url}></div>`);
            }
        },
        error: function(data, s) {
            if (type == 1) {
                img_status(1, -1);
            } else if (type == 2) {
                img_status(2, -1);
            } else if (type == 3) {
                msc.ui.dialog.error("上传失败，请重试");
                if (p.find('.file_img').length > 0) {
                    p.find('.file_img').show();
                } else p.append('<div class="div_file_img error"><b></b><img class="file_img" src="//static.meishichina.com/v6/img/blank.gif"></div>');
            }
        },
        complete: function() {
            i++;
            if (i < f.length) upload_img(f, type, i, p)
            else {
                if (type == 1) img_status(1, 2);
                else if (type == 2) img_status(2, 2);
            }
        }
    });
}
function img_status(i, t, n) {
    i = (i == 1) ? $("#multi_cover_status") : $("#multi_step_status");
    n = (n > 1) ? n: 1;
    if (t == 0) {
        i.html('<span class="step_doing" title="正在上传中..."></span>本次共选择<b class="s1">' + n + '</b>张图片，成功<b class="s2">0</b>张，失败<b class="s3">0</b>张。')
    } else if (t == 1) {
        i.find('.s2').html(parseInt(i.find('.s2').html()) + n);
    } else if (t == -1) {
        i.find('.s3').html(parseInt(i.find('.s3').html()) + n);
    } else if (t == 2) {
        i.find('.step_doing').remove();
        i.append('上传完毕！支持鼠标拖拽调整步骤顺序')
    }
}
$(".things_copyright span").click(function() {
    $(this).addClass('on').siblings().removeClass('on');
    $("#things_copyright").val($(this).attr("data-value"));
});
$("#savebtn").click(function() {
    if ($('input[name=subject]').val() === '') {
        msc.ui.dialog.error("请输入菜谱名称");
        $('input[name=subject]').focus();
    }else if ($('input.liao:first').val() == '') {
        msc.ui.dialog.error("请完善食材明细");
    } else if (check_step() == 1) {
        msc.ui.dialog.error("请完善菜谱步骤");
    } else if ($('.step_doing').length > 0) {
        msc.ui.dialog.error("有图片正在上传中，请耐心等待...");
    } else if ($("input[name=level]").val() == '0') {
        msc.ui.dialog.error("请选择制作难度");
    } else if ($("input[name=during]").val() == '0') {
        msc.ui.dialog.error("请选择需要时间");
    } else if ($("input[name=cuisine]").val() == '0') {
        msc.ui.dialog.error("请选择口味");
    }else {
        var j_cookbook = getdata();
        var ingredient_groups = getIngredient_groups();
        var stepId = getStep();
        j_cookbook.condiments = ingredient_groups;
        j_cookbook.productions = stepId;
        // console.log(j_cookbook)
        $.ajax({
            url: '/recipes/doAddRecipes',
            type: "POST",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: $.toJSON(j_cookbook),
            success: function (e) {
                if (e.status==200) {
                    location.href="/menu-list.html"
                } else {
                   alert("添加失败");
                   location.href="/menu-list.html"
                }
            }
        });
    }

});
$(document).click(function(e) {
    var con1 = $('.options_box div, .options_item div:eq(2)');
    if (!con1.is(e.target) && con1.has(e.target).length === 0) $(".options_item div").hide();
});
function delAliYunObject(e) {
    var img = e.split("?");
    $.get(msc.tools.getAjaxUrl({
            ac: "recipe",
            op: "delAliYunObject"
        }), {
            'img': img[0]
        },
        function() {},
        "json");
}
function orderNumber() {
    $("#dragsort blockquote").each(function() {
        $(this).find(".J_step_num").html(($(this).index() + 1) + "、");
    });
}
function add_stepimg_number() {
    var i = '';
    var n = 0;
    var d = $("#dragsort blockquote:last");
    if (d.find('input[name=step_img]').val() != '' || d.find('textarea').val() != '') {
        n = -1;
    } else {
        for (i = d.index(); i > -1; i--) {
            if ($("#dragsort blockquote:eq(" + i + ")").find('input[name=step_img]').val() != '' || $("#dragsort blockquote:eq(" + i + ")").find('textarea').val() != '') {
                n = i + 1;
                break;
            }
        }
    }
    return n;
}
function check_step() {
    var istep = 0;
    $('textarea[name="note"]').each(function() {
        if ($(this).val().replace(/(^\s*)|(\s*$)/g, "") == '') {
            istep = 1;
            return;
        }
    });
    return istep;
}
function getdata() {
    var arr = {};
    arr.menuName = $("[name='subject']").val();
    arr.described = $("[name='message']").val();
    arr.difficulty = $("[name='level']").val();
    arr.flavor = $("[name='cuisine']").val();
    arr.technology = $("[name='technics']").val();
    arr.needTime = $("[name='during']").val();
    arr.kitchenware= $("[name='cookers']").val();
    arr.condiments;
    arr.productions;
    arr.tips = $("[name='tips']").val();
    var str="";
    $("input[name='allpic']").each(function(i) {
        if (i==0)
             str =str+$(this).val();
    });
    arr.finishedImg = str;
    return arr;
}
function getStep() {
    var bbb = new Array();
    $("li.step blockquote").each(function () {
        if (step_img = $(this).find('input.J_imghidden').val()!=""&&$(this).find('textArea.textArea').val()!="" )
        {
            let step_img = $(this).find('input.J_imghidden').val();
            let note = $(this).find('textArea.textArea').val();
            bbb.push({stepImage:step_img,stepDescription:note})
        }

    })
    return bbb;
}
function getIngredient_groups(){
    var aas = new Array();
    $("li.ingredient blockquote").each(function() {
        var that = $(this);
        var aar = {};
        that.find('div').each(function(i) {
            if ($(this).find('input.liao').val() != ''){
                let groupName = $(that).find('p span').html();
                let ingredientsName=$(this).find('input.liao').val();
                let dosage = $(this).find('input.yongliang').val();
                aas.push({groupName:groupName,ingredientsName:ingredientsName,dosage:dosage});
            }
        });
    });
    return aas;
}

// if (! (navigator.userAgent.indexOf('Trident') > -1)) {
//     window.onbeforeunload = onbeforeunload_handler;
// }
// function onbeforeunload_handler() {
//     if (ifbtn == 0) return "您输入的数据可能不会被保存";
// }
(function(original) {
    jQuery.fn.clone = function() {
        var result = original.apply(this, arguments),
            my_textareas = this.find('textarea').add(this.filter('textarea')),
            result_textareas = result.find('textarea').add(result.filter('textarea')),
            my_selects = this.find('select').add(this.filter('select')),
            result_selects = result.find('select').add(result.filter('select'));
        for (var i = 0,
                 l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
        for (var i = 0,
                 l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;
        return result;
    };
})(jQuery.fn.clone);

$("#tuichu").click(function() {
    location.href="/menu-list.html"
});






















